package com.a3g.findnumber;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;




import com.a3g.findnumber.entity.AppRater;
import com.a3g.findnumber.entity.MusicService;
import com.facebook.Response;
import com.facebook.Request;
import com.facebook.Session;
import com.facebook.SessionLoginBehavior;
import com.facebook.SessionState;


public class FinishAct extends Activity implements OnClickListener {

	Button restart_btn, facebook_btn;
	
	private Button rateButton;

	TextView scoreField;

	TextView hightScoreField;

	Session fbSession;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		this.initial();

	}

	private void initial() {
		setContentView(R.layout.game_end);

		this.scoreField = (TextView) findViewById(R.id.scoreField);
		this.hightScoreField = (TextView) findViewById(R.id.hightScoreField);

		restart_btn = (Button) findViewById(R.id.retryBtn);
		facebook_btn = (Button) findViewById(R.id.faceBtn);
		rateButton = (Button) findViewById(R.id.rateButton);

		restart_btn.setOnClickListener(this);
		facebook_btn.setOnClickListener(this);
		rateButton.setOnClickListener(this);

		Intent finishIntent = getIntent();
		int score = finishIntent.getIntExtra("Score", 0);
		int bestScore = this.getHightScore(score);

		this.setScore(score);
		this.setHighScore(bestScore);

	}

	private int getHightScore(int recentScore) {

		int bestScore = 0;

		SharedPreferences saveHighScore = this.getSharedPreferences(
				"DBHighScore", Context.MODE_PRIVATE);
		if (saveHighScore == null) {

			bestScore = recentScore;
			this.saveHighScore(saveHighScore, bestScore);

		} else {
			int highScore = saveHighScore.getInt("highScore", 0);

			if (recentScore > highScore) {
				bestScore = recentScore;
				this.saveHighScore(saveHighScore, bestScore);
			} else {
				bestScore = highScore;
			}
		}

		return bestScore;
	}

	public void saveHighScore(SharedPreferences saveHighScore, int bestScore) {
		Editor editor = saveHighScore.edit();
		editor.putInt("highScore", bestScore);
		editor.commit();
		editor.clear();
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.retryBtn:
			Intent mainActivity = new Intent(getApplicationContext(),
					StartAct.class);
			mainActivity.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
			startActivity(mainActivity);
			break;
		case R.id.faceBtn:
			showToastMessage("Share Facebook.");
			connectToFB();
			break;
			
		case R.id.rateButton: {
			AppRater.app_launched(this);
			break;
		}

		}
		
		

		// finish();

	}

	void showToastMessage(String message) {
		Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT)
				.show();
	}

	private void setScore(int score) {
		this.scoreField.setText("SCORE : " + score);
	}

	private void setHighScore(int hightScore) {
		this.hightScoreField.setText("BEST : " + hightScore);
	}

	private Bitmap captureScreen() {
		Log.e("Capture", "Start Capture Background Image");

		View rootView = findViewById(android.R.id.content).getRootView();
		rootView.setDrawingCacheEnabled(true);
		return rootView.getDrawingCache();
	}

	/** Facebook **/
	// ---------------------------------------
		Session.StatusCallback mCallbacks = new Session.StatusCallback() {
			@Override
			public void call(Session session, SessionState state,
					Exception exception) {
				onSessionStateChange(session, state, exception);
				Log.e("Facebook", "Exception call(): "+ exception);
			}
		};

		@Override
		public void onActivityResult(int requestCode, int resultCode, Intent data) {

			super.onActivityResult(requestCode, resultCode, data);
			
			if (fbSession != null) {
				fbSession.onActivityResult(this, requestCode, resultCode, data);
			}
		}

		
		private void postPhoto() {

			Log.e("Facebook", "Post Photo");

			Bitmap	image = this.captureScreen();
			
			if (null==image) {
				image = BitmapFactory.decodeResource(this.getResources(), R.drawable.game_icon);
			}
			
//			Bitmap image = BitmapFactory.decodeResource(this.getResources(), R.drawable.a3g);
			
//			Log.e("Facebook", "Post Photo, Image: " + image.getByteCount());
			
			Request request = Request.newUploadPhotoRequest(
					fbSession, image, new Request.Callback() {
						
						@Override
						public void onCompleted(Response response) {
							Log.e("Facebook", "Publish complete: " + response.toString());
						}
					});
			
			request.executeAsync();
		}


		private void performPublish(boolean allowNoSession) {

			Log.e("Facebook", "performPublish()");
					
			if (fbSession != null && fbSession.isOpened()) {
			
				postPhoto();
					
			} else if (allowNoSession) {
				
				Log.e("Facebook", "noSession = true");
				postPhoto();
			}
		}

		// /////-------------------------------------------////
		public void connectToFB() {
			Log.e("connectToFB", " connectToFB 01");
			List<String> permissions = new ArrayList<String>();
			permissions.add("publish_actions");
			permissions.add("publish_stream");
			//permissions.add("read_stream");
			fbSession = new Session.Builder(this).build();
			fbSession.addCallback(mCallbacks);
			Session.OpenRequest openRequest = new Session.OpenRequest(this);
			openRequest.setLoginBehavior(SessionLoginBehavior.SUPPRESS_SSO);
			openRequest.setRequestCode(Session.DEFAULT_AUTHORIZE_ACTIVITY_CODE);
			
			openRequest.setPermissions(permissions);
			
			fbSession.openForPublish(openRequest);
			Log.e("connectToFB", " openForPublish - OpenRequest");

		}

		private void onSessionStateChange(Session session, SessionState state,
				Exception exception) {
			if (session != fbSession) {
				return;
			}

			if (state.isOpened()) {
				// Log in just happened.
				Toast.makeText(getApplicationContext(), "session opened", Toast.LENGTH_SHORT).show();
				Log.e("Facebook", "Open: " + session.isOpened());
				this.fbSession = session;
				performPublish(true);
				Log.e("performPublish", "performPublish");
				
			} else if (state.isClosed()) {
				// Log out just happened. Update the UI.
				Toast.makeText(getApplicationContext(), "session closed",
						Toast.LENGTH_SHORT).show();
			}
		}
	
		@Override
		public void onPause() {
		    if (StartAct.isApplicationSentToBackground(this)){
		        // Stop music when Home Key being Pressed 
		    	stopService(new Intent(this, MusicService.class));
		    }
		    super.onPause();
		}

}